/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.store.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.dto.DTO;
import com.javaeye.store.dto.Materials;
import com.javaeye.common.web.PageInfo;

public class MaterialsDAOHibernate extends HibernateDaoSupport implements MaterialsDAO {
	
	/**
	 * 取得在库品的实时库存数量
	 * @param code 在库品编码
	 * @return 实时库存数量
	 */
	/*@SuppressWarnings("unchecked")
	public float getCurrentAtStroeNumber(String code) {
		final String queryString = "select m.number from Materials m where m.code=?";
		List result = getHibernateTemplate().find(queryString, code);
		if (result == null || result.size() == 0) {
			return 0;
		}
		return (Float)result.get(0);
	}*/
	
	@SuppressWarnings("unchecked")
	public List<Materials> getAutoCompleteMaterials(final String name, final int size) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria crit = session.createCriteria(Materials.class);
				crit.add(Restrictions.like("code", name.trim() + "%"));
				crit.setFirstResult(0);
				crit.setMaxResults(size);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public List<Materials> getHasDefectiveMaterials() {
		final String queryString = "from Materials m where m.defectiveNumber > 0";
		List result = getHibernateTemplate().find(queryString);
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<Materials> getMaterialsExportList(final Materials condition) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				Criteria crit = session.createCriteria(Materials.class);
				//这里为了去除重复记录
				crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
				initCriteria(crit, condition);
				crit.setFetchMode("skuDetails", FetchMode.JOIN);
				//crit.setFetchMode("customFields", FetchMode.JOIN);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				Materials materials = (Materials)contidions;
				Criteria crit = session.createCriteria(Materials.class);
				
				initCriteria(crit, materials);
				
				crit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)crit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				crit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	private void initCriteria(Criteria crit, Materials materials) {
		crit.add(Restrictions.eq("inuse", 1));
		/*String code = materials.getCode().trim();
		if (!"".equals(code)) {
			crit.add(Restrictions.like("code", code + "%"));
		}*/
		String name = materials.getName().trim();
		if (!"".equals(name) && !"-1".equals(name)) {
			crit.add(Restrictions.like("name", "%" + name + "%"));
		}
		String type = materials.getType().trim();
		if (!"".equals(type)) {
			crit.add(Restrictions.like("type", type + "%"));
		}
		int rootCategory = materials.getRootCategory().getId();
		if (-1 != rootCategory) {
			crit.createCriteria("rootCategory")
			.add(Restrictions.eq("id", rootCategory));
		}
		
		int category = materials.getCategory().getId();
		if (-1 != category) {
			crit.createCriteria("category")
			.add(Restrictions.eq("id", category));
		}
		
	}
	
	@Override
	public void saveMaterials(Materials materials) {
		materials.setInuse(1);
		getHibernateTemplate().saveOrUpdate(materials);
		//logger.debug("Materials id set to: " + materials.getId());
	}

	@Override
	public Materials getMaterials(int materialsId) {
		Materials materials = (Materials)getHibernateTemplate().get(Materials.class, materialsId);
		//Hibernate.initialize(materials.getCustomFields());
		Hibernate.initialize(materials.getSkuDetails());
		return materials;
	}
	
	@SuppressWarnings("unchecked")
	public long getCountByCategoryId(int categoryId) {
		final String queryString = "select count(m.id) from Materials m where m.category.id=? and m.inuse = 1";
		List result = getHibernateTemplate().find(queryString, categoryId);
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}
	
	@SuppressWarnings("unchecked")
	public Materials getMaterialsByCode(String code) {
		final String queryString = "from Materials m where m.code=?";
		List result = getHibernateTemplate().find(queryString, code);
		if (result == null || result.size() == 0) {
			return null;
		}
		Materials materials = (Materials)result.get(0);
		//Hibernate.initialize(materials.getCustomFields());
		Hibernate.initialize(materials.getSkuDetails());
		return materials;
	}

	@Override
	public void removeMaterials(int materialsId) {
		
		Materials materials = (Materials)getHibernateTemplate().load(
				Materials.class, materialsId);
		//getHibernateTemplate().delete(o);
		materials.setInuse(0);
		getHibernateTemplate().saveOrUpdate(materials);
		
	}

}
